var ctx=window.daijia.ctx; 
var week=window.daijia.week; 
var latitude,longitude;
var city=null;
var phone=null;

var wxAppId=window.daijia.wxAppId; 
var wxServer=window.daijia.wxServer; 

var height = document.documentElement.clientHeight;
var selectParam_div_height=height*0.7;


if(is_weixin()){

	var base_url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+wxAppId+"&redirect_uri="+URLEncode(''+wxServer+'m/rentOrder')+"&response_type=code&scope=snsapi_base&state=null#wechat_redirect";

	var _obj = UrlGet();
	
	if(_obj.code){
		$.post(ctx+'/wx/v1/userInfo',{'code':_obj.code},function(data){
			if(data.success){
				phone=data.object.phone;
			}
			else{

			}
		},'json');
	}
	else{
		window.location.replace(base_url);
	}
}
else{
	$.post(ctx+'/m/weixinIsLogin',{},function(data){
		if(data.success){
			phone=data.object.phone;
		}
		else{

		}
	},'json');
}

$(document).ready(function(){
	
	var backlayer ="<div id='loadblacklayer'><div style='text-align: center;margin-left: auto;margin-right: auto;width: 140px; border-radius:4px;height: 140px; background-color:#000; color: #FFF;'><img id='picture' src='"+ctx+"/assets/img/q.gif'  width='100px'/><p id='writing'>请稍等...</p></div></div>";
	$("body").append(backlayer);
	var height =  $("body").height()/2 - 70;
	$('#loadblacklayer').find("div").css({"margin-top":height});
	$('#loadblacklayer').css({"z-index":"99","background":"#fff","opacity":"0.5","position":'absolute',"top":0,"width":"100%","height":"100%"});
	$(window).resize(function(){
		var height =  $("body").height()/2 - 70;
		$('#loadblacklayer').find("div").css({"margin-top":height});
	});
	$('#loadblacklayer').hide();
	
	$("#qucheTime").datetimepicker({format: 'yyyy-mm-dd HH:ii', language: 'zh-CN', minView: 'hour', pickDate: true, pickTime: false, inputMask: false, autoclose: true });
    $("#huancheTime").datetimepicker({format: 'yyyy-mm-dd HH:ii', language: 'zh-CN', minView: 'hour', pickDate: true, pickTime: false, inputMask: false, autoclose: true });
	
	$("#selectParam_div").css("height",""+selectParam_div_height+"px");
	
	$('.range-slider').jRange({
		from: 0,
		to: 1200,
		step: 20,
		scale: [0,200,400,600,800,1000,'不限'],
		format: '%s',
		width: 300,
		showLabels: false,
		isRange : true
	});
	
	//点击筛选
	$("#showParam").click(function(){
		if($("#selectParam_div").is(":hidden")){
			$("#selectParam_div").slideDown();
		}
		else{
			$("#selectParam_div").slideUp();
		}
	});
	
	//选择城市
	$("#selectCity_select").change(function(){
		if($(this).val()!=''){
			city=$(this).val();
			loadCars(true);
		}
	});
	
	//点击价格
	$("#clickPriceSort").click(function(){
		if($("#price_sort_div").is(":hidden")){
			$("#price_sort_div").show();
		}
		else{
			$("#price_sort_div").hide();
		}
	});
	
	//选择价格排序
	$("input[name=priceSort]").change(function(){
		loadCars(true);
		if($(this).val=="0"){
			$("#clickPriceSort img").attr("src",ctx+"/assets/img/jiage_desc.png")
		}
		else{
			$("#clickPriceSort img").attr("src",ctx+"/assets/img/jiage_asc.png")
		}
	});
	
	//点击车辆类型
	$(".car_type").click(function(){
		if($(this).hasClass('car_type_checked')){
			$(this).removeClass('car_type_checked');
			$(this).find("img").attr("src",ctx+"/assets/img/jingji_icon.png")
		}
		else{
			$(this).addClass('car_type_checked');
			$(this).find("img").attr("src",ctx+"/assets/img/jingji_icon_checked.png")
		}
	});
	
	//加载更多
	$(document).on('click','#page',function(){
		loadCars(false);
	});
	
	//点击车辆
	$(document).on('click','.xiadan',function(){
		
		$("#modal_carId").val($(this).attr('data-id'));
		$('#modal_picture').attr("src",$(this).attr('data-picture'));
		$("#modal_brandName").html($(this).attr('data-brandName'));
		$("#modal_type").html($(this).attr('data-type'));
		$("#modal_xianxing").html($(this).attr('data-xianxing'));
		$("#modal_seating").html($(this).attr('data-seating')+"座");
		$("#modal_price").html("￥"+$(this).attr('data-price')+"元/天");
		
		
		var today = new Date(); 
		$("#qucheTime").val(getNowFormatDate(today));
		today.setDate(today.getDate()+1);
		$("#huancheTime").val(getNowFormatDate(today));
		
		$('.xiadan_modal').modal();
	});
	
	//确认下单
	$("#xiadan_ok").click(function(){
		
		if($("#qucheTime").val()>$("#huancheTime").val()){
			$.scojs_message("取车时间不能大于还车时间", $.scojs_message.TYPE_ERROR);
			return false;
		}
		
		if(null==phone || phone==""){
			window.location.href=ctx+"/wx/v1/bind?returnUrl="+URLEncode(ctx+'/m/rentOrder')+"";
		}else{
			$('#loadblacklayer').show();
			$.post(
				ctx+'/m/postRentOrder',
				{
					'phone':phone,
					'carId':$("#modal_carId").val(),
					'qucheTime':$("#qucheTime").val(),
					'huancheTime':$("#huancheTime").val()
				},
				function(data){
					if(data.success){
						$('#loadblacklayer').hide();
						window.location.href=ctx+'/wx/v1/successes';
					}else{
						if(data.errorcode=="PHONENOTEXISTS"){
							window.location.href=ctx+"/wx/v1/bind?returnUrl="+URLEncode(ctx+'/m/rentOrder')+"";
						}
						else{
							$.scojs_message(data.message, $.scojs_message.TYPE_ERROR);
						}
					}
			});	
		}
	});
	
	$("#close_panel").click(function(){
		$("#selectParam_div").slideUp();
	});
	
	$("#start_search").click(function(){
		loadCars(true);
	});
	
	locationMe();
	
	
});
function locationMe(){
	if(navigator && navigator.geolocation){
		navigator.geolocation.getCurrentPosition(function (position) {
		    var coords = position.coords;
			latitude=coords.latitude;
			longitude=coords.longitude;
			translateCoords(coords);
		},function(error){
		    switch(error.code) {
		        case error.TIMEOUT:
		        	$.scojs_message("定位失败，请手动选择城市。", $.scojs_message.TYPE_ERROR);
		          	break;
		        case error.POSITION_UNAVAILABLE:
		        	$.scojs_message("定位失败，请手动选择城市。", $.scojs_message.TYPE_ERROR);
		            break;
		        case error.PERMISSION_DENIED:
		        	$.scojs_message("定位失败，请手动选择城市。", $.scojs_message.TYPE_ERROR);
		            break;
		        case error.UNKNOWN_ERROR:
		        	$.scojs_message("定位失败，请手动选择城市。", $.scojs_message.TYPE_ERROR);
		            break;
		    }
		},{enableHighAccuracy:true,timeout:3000,maximumAge:4000});
	}else{
		$.scojs_message("定位失败，请手动选择城市。", $.scojs_message.TYPE_ERROR);
	}
	
}

function translateCoords(coords){
	
	var loc = coords.latitude+','+coords.longitude;
	
	var param = {ak:'0Bf0928e769210fd88e064cd0cdf84d8',location:loc,output:'json',pois:0,coordtype:'wgs84ll'};
	    
	$.ajax({
		url:"https://api.map.baidu.com/geocoder/v2/",
		type:"GET",
		async:false,
		dataType:'jsonp',
		jsonp:'callback',
		data:param,
		success:function(resp){
			if(null!=resp && ""!=resp && resp.status == 0){
				city=resp.result.addressComponent.city;
				$("#selectCity_select option").each(function(index,element){
					if($(element).text()==city){
						$("#selectCity_select").val(city);
						loadCars(true);
						return false;
					}
				});
			}
		},
	});
}


var page=0;
function loadCars(isNew){
	if(city==null){
		$.scojs_message("请先选择城市。", $.scojs_message.TYPE_ERROR);
		return false;
	}
	
	if(!$("#selectParam_div").is(":hidden")){
		$("#selectParam_div").slideUp();
	}
	
	if(isNew){
		page=0;
	}
	
	//价格
	var minmax=$(".range-slider").val();
	var douhao=minmax.indexOf(",");
	var min=minmax.substr(0,douhao);
	var max=minmax.substr(douhao+1,minmax.length);
	if(max==1200){
		max=null;
	}
	//品牌
	var brandId=$("#selectBrand_select").val();
	
	//手动、自动
	var transmission=null;
	var transmissionATChecked=$("input[name=transmissionAT]").is(":checked");
	var transmissionMTChecked=$("input[name=transmissionMT]").is(":checked");
	if(transmissionATChecked && !transmissionMTChecked){
		transmission=0;
	}
	else if(!transmissionATChecked && transmissionMTChecked){
		transmission=1;
	}
	
	//类型
	var carTypeIdsArr=[];
	var carTypeIds=null;
	$(".car_type_checked").each(function(index,element){
		carTypeIdsArr.push($(element).attr("data-value"));
	});
	if(null!=carTypeIdsArr && carTypeIdsArr.length>0){
		carTypeIds=carTypeIdsArr.join(",");
	}
	
	
	$('#loadblacklayer').show();
	
	$.ajax({
        type: "POST",
        async:true,
        url: ctx+"/m/queryRentalCars",
        data: {
        	'city':city,
        	'min':min,
        	'max':max,
        	'transmission':transmission,
        	'carTypeIds':carTypeIds,
        	'brandId':brandId,
        	'priceSort':$("input[name=priceSort]:checked").val(),
        	'page':page,
        	'limit':6
        },
        dataType: "json",
        success: function(data){
        	if(isNew){
        		$("#content").html('<div class="list-group"></div>');
        	}
        	else{
        		$("#page").remove();
        	}
        	
        	if(data.totalElements>0){
        		$(data.content).each(function(index,element){
        			
        			var picture=element.picture;
        			if(null==picture || picture==""){
        				picture=ctx+"/assets/img/zuche_weixin_nopicture.jpg";
        			}
        			
        			var xianxing='';
        			if(element.limitLine=="0" || element.limitLine==week){
        				xianxing=element.carNumber;
        			}else{
        				if(element.limitLine=="1"){
        					xianxing="周一限行";
        				}
        				else if(element.limitLine=="2"){
        					xianxing="周二限行";
        				}
						else if(element.limitLine=="3"){
							xianxing="周三限行";					
						}
						else if(element.limitLine=="4"){
							xianxing="周四限行";
						}
						else if(element.limitLine=="5"){
							xianxing="周五限行";
						}
        			}
        			
        			var type=element.type;
        			if(null!=type && type!=''){
        				type=element.type+'/'+element.displacement+element.transmissionCase;
        			}
        			
        			var content='<a href="javascript:;" class="list-group-item xiadan" data-id="'+element.id+'" data-picture="'+picture+'" data-brandName="'+element.brandName+'" data-type="'+type+'" data-xianxing="'+xianxing+'" data-seating="'+element.seating+'" data-price="'+element.price+'">'+
			    					'<div class="row">'+
										'<div class="col-xs-12" style="padding: 0px;">'+
											'<div class="col-xs-4">'+
												'<img width="120" height="60" src='+picture+' />'+
											'</div>'+
											'<div class="col-xs-8 content_text">'+
												'<div class="col-xs-12 content_text1">'+
													'<p class="text-left content_text2" style="margin:0px;"><strong>'+element.brandName+'</strong></p>'+
												'</div>'+
												'<div class="row">'+
													'<div class="col-xs-7" style="padding-right:0px;">'+
														'<p class="text-left" style="margin:0px;">'+type+' </p>'+
													'</div>'+
													'<div class="col-xs-5" style="padding-left:0px;">'+
														'<p class="text-right" style="margin:0px;">'+xianxing+' </p>'+
													'</div>'+
												'</div>'+
												'<div class="row">'+
													'<div class="col-xs-4" style="padding-right:0px;">'+
														'<p class="text-left content_text3">'+element.seating+'座 </p>'+
													'</div>'+
													'<div class="col-xs-8" style="padding-left:0px;">'+
														'<p class="text-right content_text4"><strong>￥'+element.price+'元/天</strong> </p>'+
													'</div>'+
												'</div>'+
											'</div>'+
										'</div>'+
									'</div>'+
								'</a>';
					$("#content .list-group").append(content);
        		});
        		
        		if(data.last){
        			$("#content").append('<center>没有更多车辆</center>');
        		}
        		else{
        			$("#content").append('<div class="col-lg-12"><input type="button" class="btn btn-primary btn-block" id="page" value="加载更多" /></div>');
        			page++;
        		}
        		
        	}
        	else{
        		var content='<div class="list-group">'+
				        		'<a href="#" class="list-group-item">'+
				        			'<center>'+
						        	    '<h4 class="list-group-item-heading">没有找到符合条件的车辆</h4>'+
						        	    '<p class="list-group-item-text">请重新选择城市或更改筛选条件</p>'+
					        	    '</center>'+
				        	    '</a>'+
				        	 '</div>';
        		$("#content").append(content);
        	}
        	
        	$('#loadblacklayer').hide();
        	
        }
    });
}


function getNowFormatDate(date) {
	
    var seperator1 = "-";
    var seperator2 = ":";
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();
    
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    if (hour >= 0 && hour <= 9) {
    	hour = "0" + hour;
    }
    if (minute >= 0 && minute <= 9) {
    	minute = "0" + minute;
    }
    var currentdate = year + seperator1 + month + seperator1 + strDate
            + " " + hour + seperator2 + minute;
    return currentdate;
}

function URLEncode (clearString) {
	var output = '';
		var x = 0;
	clearString = clearString.toString();
	var regex = /(^[a-zA-Z0-9-_.]*)/;
	while (x < clearString.length) {
 		var match = regex.exec(clearString.substr(x));
 		if (match != null && match.length > 1 && match[1] != '') {
     		output += match[1];
   			x += match[1].length;
 		}else{
   			if (clearString.substr(x, 1) == ' ') {
     		//原文在此用 clearString[x] == ' ' 做判断, 但ie不支持把字符串当作数组来访问, 
    		//修改后两种浏览器都可兼容 
     		output += '+';
   			}
			else{
    		var charCode = clearString.charCodeAt(x);
     		var hexVal = charCode.toString(16);
    		output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
  			}
			x++;
 		}
	}
	 return output;
}

function is_weixin(){
    var ua = navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i)=="micromessenger") {
        return true;
    } else {
        return false;
    }
}

function UrlGet() {
    var args = {};
    var query = location.search.substring(1);//取地址栏中问号后第一个参数
    var pairs = query.split("&");
    for (var i = 0; i < pairs.length; i++) {
        var pos = pairs[i].indexOf('=');
        if (pos == -1) continue;
        var argname = pairs[i].substring(0, pos);
        var value = pairs[i].substring(pos + 1);
        value = decodeURIComponent(value);
        args[argname] = value;
    }
    
    return args;
}